import type { MenuProps } from "antd";
import { useNavigate } from "react-router-dom";
import React, { useState, useEffect } from "react";
import type { APP } from "@/pages/hosting/typings";
import { postAppInfo } from "@/services/hosting/api";
import { postRollBack, postRollBackRemove } from "@/services/hosting/api";
import {
    Table,
    Tag,
    Space,
    Menu,
    Typography,
    Statistic,
    Button,
    Popconfirm,
    message,
    theme
} from "antd";
import {
    ClockCircleOutlined,
    RocketOutlined,
    CodeOutlined,
    DeleteOutlined
} from "@ant-design/icons";


const { Title, Text } = Typography;

interface Props {
    onRollbackSuccess?: () => void;
}

const Record: React.FC<Props> = ({ onRollbackSuccess }) => {
    const params = new URLSearchParams(location.search);
    const navigate = useNavigate();
    const [selectedPeriod, setSelectedPeriod] = useState<string>("今天");
    const timePeriods = ["今天", "昨天", "一周内", "一个月内", "更早"];
    const stype = params.get("type");
    const nodeId = params.get("nodeId");
    const [loading, setLoading] = useState(true);
    const [isDeployVisible, setIsDeployVisible] = useState(false);
    const [isDeployMounted, setIsDeployMounted] = useState(false);
    const [app, setApp] = useState<APP | null>(null);
    const [show404, setShow404] = useState(false);
    const { useToken } = theme;
    const appId: string = params.get("appId") || "";
    const [appInfo, setAppInfo] = useState() as any;
    const [deleteLoading, setDeleteLoading] = useState<{[key: string]: boolean}>({});
    
    const initAppInfo = async () => {
        setLoading(true);
        setIsDeployMounted(false);
        setIsDeployVisible(false);
        try {
            const res = await postAppInfo({ app_id: appId }, stype as string, nodeId as string, navigate);
            if (res.status === "success") {
                setApp(res.message.now_data);
                setAppInfo(res.message as any)
                setLoading(false);
                return res.message; // 返回数据以便后续处理
            } else if (res.status === "error") {
                console.log("渲染404");
                setShow404(true);
                setLoading(false);
            }
        } catch (err) {
            message.error("应用获取失败！");
            console.log("应用数据获取失败：", err);
            history.back();
        }
    };

    const groupByTimePeriod = (data: any[]) => {
        const now = new Date();
        const today = new Date(
            now.getFullYear(),
            now.getMonth(),
            now.getDate(),
        );
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);
        const oneWeekAgo = new Date(today);
        oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
        const oneMonthAgo = new Date(today);
        oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
        const groups: any = {
            今天: [],
            昨天: [],
            一周内: [],
            一个月内: [],
            更早: [],
        };
        data.forEach((item) => {
            if (item.deploy_time) {
                const deployDate = new Date(
                    item.deploy_time.replace(/-/g, "/"),
                );
                if (deployDate >= today) {
                    groups["今天"].push(item);
                } else if (deployDate >= yesterday) {
                    groups["昨天"].push(item);
                } else if (deployDate >= oneWeekAgo) {
                    groups["一周内"].push(item);
                } else if (deployDate >= oneMonthAgo) {
                    groups["一个月内"].push(item);
                } else {
                    groups["更早"].push(item);
                }
            } else {
                groups["更早"].push(item);
            }
        });
        return groups;
    };

    const createDataSource = (info: any) => {
        let sortedData = [];

        // 确保info存在且有now_data再添加到数据源开头
        if (info && info.now_data) {
            sortedData.push({
                ...info.now_data,
                id: "now",
                title: info.now_data.deploy_time,
            });
        }

        // 添加deploy_history中的历史数据
        if (info && info.deploy_history) {
            const historyData = Object.keys(info.deploy_history)
                .sort((a, b) => parseInt(b) - parseInt(a))
                .map((key) => {
                    const item = info.deploy_history[key];
                    return {
                        ...item,
                        id: key,
                        title: item.deploy_time,
                    };
                });

            // 合并当前数据和历史数据
            sortedData = [...sortedData, ...historyData];
        }
        
        return groupByTimePeriod(sortedData);
    };

    const [groupedData, setGroupedData] = useState<any>({});

    const initData = (info: any) => {
        setGroupedData(createDataSource(info));
    };

    useEffect(() => {
        initAppInfo().then(data => {
            if (data) {
                initData(data);
            }
        });
    }, []);

    const handlePeriodClick = (period: string) => {
        setSelectedPeriod(period);
    };

    const handleRollback = async (item: any) => {
        message.success(`正在回滚`);
        await postRollBack(
            { app_id: item.app_id, back_id: item.back_id },
            stype as string,
            nodeId as string,
            navigate,
        ).then((res) => {
            if (res.status === "success") {
                message.success(res.message);
                // 回滚成功后调用回调函数
                if (onRollbackSuccess) {
                    onRollbackSuccess();
                }
            } else if (res.status === "error") {
                message.error(res.message);
            }
        });
        initAppInfo().then(data => {
            if (data) {
                initData(data);
            }
        });
    };

    const handleDelete = async (item: any) => {
        // 设置当前项的删除loading状态
        setDeleteLoading(prev => ({...prev, [item.back_id]: true}));
        
        try {
            const res = await postRollBackRemove(
                { back_id: item.back_id },
                stype as string,
                nodeId as string,
                navigate,
            );
            
            if (res.status === "success") {
                message.success(res.message);
            } else if (res.status === "error") {
                message.error(res.message);
            }
        } catch (error) {
            message.error("删除失败");
        } finally {
            // 重置当前项的删除loading状态
            setDeleteLoading(prev => {
                const newLoading = {...prev};
                delete newLoading[item.back_id];
                return newLoading;
            });
        }
        
        // 刷新数据
        initAppInfo().then(data => {
            if (data) {
                initData(data);
            }
        });
    };

    const batchDeleteClick = async () => {

    };

    const menuItems: MenuProps["items"] = timePeriods
        .filter(
            (period) => groupedData[period] && groupedData[period].length > 0,
        )
        .map((period) => ({
            key: period,
            label: (
                <div
                    style={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                        width: "100%",
                    }}
                >
                    <span>{period}</span>
                    {groupedData[period].length}
                </div>
            ),
        }));

    const columns = [
        {
            title: "序号",
            key: "index",
            width: 50,
            align: "center" as const,
            render: (_: any, record: any, index: number) => {
                // 如果是当前版本，显示特殊标签
                if (record.id === "now") {
                    return <Tag color="#2ed573">当前版本</Tag>;
                }
                // 其他版本显示序号
                return index + 1;
            },
        },
        {
            title: "发布时间",
            dataIndex: "deploy_time",
            key: "deploy_time",
            width: 150,
            align: "center" as const,
            render: (text: string) => (
                <Text type="secondary">{text}</Text>
            ),
            defaultSortOrder: "descend" as "descend",
        },
        {
            title: "版本",
            dataIndex: "version",
            key: "version",
            width: 100,
            align: "center" as const,
            render: (text: string) => {
                return text ? text : "--";
            },
        },
        {
            title: "备注",
            align: "center" as const,
            dataIndex: "notes",
            key: "notes",
            width: 800,
            fixed: "right",
            render: (text: string) => (
                <Text
                    ellipsis={{ tooltip: text }}
                    style={{ width: "100%", alignItems: "left" }}
                >
                    {text || "无备注"}
                </Text>
            ),
        },
        {
            title: "操作",
            key: "action",
            width: 80,
            align: "center" as const,

            render: (_: any, record: any) => {
                if (record.id !== "now") {
                    return (
                        <Space size="small">
                            <Popconfirm
                                title="确定要回滚到此版本吗？"
                                onConfirm={() => handleRollback(record)}
                                okText="确定"
                                cancelText="取消"
                            >
                                <Button size="small">回滚</Button>
                            </Popconfirm>
                            <Popconfirm
                                title="确定要删除这条记录吗？"
                                onConfirm={() => handleDelete(record)}
                                okText="确定"
                                cancelText="取消"
                            >
                                <Button 
                                    size="small" 
                                    danger
                                    loading={deleteLoading[record.back_id] || false}
                                >
                                    删除
                                </Button>
                            </Popconfirm>
                        </Space>
                    );
                } else {
                    return <Space size="small"></Space>;
                }
            },
        },
    ];
    const renderStats = () => {
        const totalDeployments = Object.values(groupedData).reduce(
            (total: number, group: any) => total + group.length,
            0,
        );
        const successCount = Object.values(groupedData)
            .flat()
            .filter((item: any) => item.status === "success").length;
        const successRate =
            totalDeployments > 0
                ? ((successCount / totalDeployments) * 100).toFixed(1)
                : 0;
        return (
            <Statistic
                title="总发布次数"
                value={totalDeployments}
                valueStyle={{ color: "#1890ff" }}
            />
        );
    };

    return (
        <div
            style={{
                minHeight: "60vh",
                margin: "16px",
                boxShadow:
                    "0 4px 12px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.08), 0 0 0 1px rgba(0, 0, 0, 0.05)",
                borderRadius: "8px",
                backgroundColor: "#fff",
                overflow: "hidden",
            }}
        >
            <div style={{ display: "flex", height: "64vh" }}>
                <div
                    style={{
                        width: 280,
                        flexShrink: 0,
                        background: "#fafafa",
                        borderRight: "1px solid #f0f0f0",
                        display: "flex",
                        flexDirection: "column",
                    }}
                >
                    <div
                        style={{
                            padding: "20px",
                            fontSize: 18,
                            fontWeight: 600,
                            color: "#262626",
                            borderBottom: "1px solid #f0f0f0",
                            background:
                                "linear-gradient(135deg, #fafafa 0%, #f0f0f0 100%)",
                        }}
                    >
                        <CodeOutlined style={{ marginRight: 8 }} />
                        时间段
                    </div>

                    <Menu
                        mode="inline"
                        selectedKeys={[selectedPeriod]}
                        items={menuItems}
                        onSelect={({ key }) => handlePeriodClick(key as string)}
                        style={{
                            borderRight: 0,
                            background: "transparent",
                            padding: "12px 0",
                            flex: 1,
                            overflow: "auto",
                        }}
                    />
                    <div style={{ marginBottom: 10 }}>
                        <Button
                            type={"text"}
                            icon={<DeleteOutlined />}
                            onClick={batchDeleteClick}
                            style={{
                                marginRight: "12px",
                            }}
                        >
                            批量删除
                        </Button>
                    </ div>
                    <div
                        style={{
                            padding: "16px",
                            borderTop: "1px solid #f0f0f0",
                            background: "#fff",
                        }}
                    >
                        {renderStats()}
                    </div>
                </div>
                <div
                    style={{
                        flex: 1,
                        padding: 24,
                        overflow: "auto",
                        background: "#fff",
                    }}
                >
                    <Title level={4} style={{ marginBottom: 20 }}>
                        {selectedPeriod
                            ? `${selectedPeriod}的发布记录`
                            : "选择时间段查看发布记录"}
                    </Title>
                    {selectedPeriod && groupedData[selectedPeriod] && (
                        <>
                            <div style={{ marginBottom: 16 }}>
                                <Text type="secondary">
                                    共 {groupedData[selectedPeriod].length}{" "}
                                    条发布记录
                                </Text>
                            </div>
                            <Table
                                columns={columns as any}
                                dataSource={groupedData[selectedPeriod]}
                                rowKey="id"
                                size="middle"
                                bordered
                                pagination={false}
                                locale={{
                                    emptyText: (
                                        <div
                                            style={{
                                                textAlign: "center",
                                                padding: 40,
                                                color: "#bfbfbf",
                                            }}
                                        >
                                            <ClockCircleOutlined
                                                style={{
                                                    fontSize: 48,
                                                    marginBottom: 16,
                                                }}
                                            />
                                            <div>暂无发布记录</div>
                                        </div>
                                    ),
                                }}
                            />
                        </>
                    )}

                    {!selectedPeriod && (
                        <div
                            style={{
                                textAlign: "center",
                                padding: 60,
                                color: "#bfbfbf",
                            }}
                        >
                            <RocketOutlined
                                style={{ fontSize: 48, marginBottom: 16 }}
                            />
                            <div>请从左侧选择时间段查看发布记录</div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

export default Record;